package com.base.taskreports.common.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.base.taskreports.common.annotation.Resubmit;
import com.base.taskreports.common.utlis.DateUtil;
import com.base.taskreports.common.utlis.DateUtils;
import com.base.taskreports.common.utlis.ResubmitLock;
import com.base.taskreports.common.utlis.response.Result;

import lombok.extern.log4j.Log4j;

/**
 * @ClassName RequestDataAspect
 * @Description 数据重复提交校验
 * @Author 张玉涛
 **/
@Log4j
@Aspect
@Component
public class ResubmitDataAspect {

    //private final static String DATA = "data";
    private final static Object PRESENT = new Object();

    @Around("@annotation(com.base.taskreports.common.annotation.Resubmit)")
    public Object handleResubmit(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取注解信息
        Resubmit annotation = method.getAnnotation(Resubmit.class);
        int delaySeconds = annotation.delaySeconds();
        Object[] pointArgs = joinPoint.getArgs();
        String key = "";
        //获取第一个参数
        String taskDate = null;
        if(pointArgs.length == 0){
            taskDate = DateUtil.getToday();
        }else {
        	if(pointArgs[0] != null ) {
        		taskDate = pointArgs[0].toString() ;
        	}else {
        		taskDate =  DateUtil.getToday();
        	}
            
        }
        //解析参数
        if (!StringUtils.isEmpty(taskDate)) {
            key = ResubmitLock.handleKey(taskDate);
        }
        //执行锁
        boolean lock = false;
        try {
            //设置解锁key
            lock = ResubmitLock.getInstance().lock(key, PRESENT);
            if (lock) {
                //放行
                return joinPoint.proceed();
            } else {
                //响应重复提交异常
                return new Result().error("不可重复提交！");
            }
        } finally {
            //设置解锁key和解锁时间
            ResubmitLock.getInstance().unLock(lock, key, delaySeconds);
        }
    }
}
